<template>
  <div class="switch-mate-box">
    <el-switch v-bind="$attrs"
               :value="row.status"
               :active-value="1"
               :inactive-value="0"
               :disabled="disabled"
               @change="handleSwitch">
    </el-switch>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  name: "SwitchMate",
  inject: ['$table'],
  props: {
    row: {
      type: Object,
      default: () => { }
    },
    enableApi: {
      type: String,
      default: ""
    },
    disableApi: {
      type: String,
      default: ""
    },
    conf: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      disabled: false
    }
  },
  methods: {
    async handleSwitch (value) {
      const message = value === 1 ? "确定启用吗？" : "确定禁用吗？";
      try {
        await this.$confirm(message, "提示", { type: 'warning' });
        await this.toggleStatus(value);
      } catch (error) {
        console.log("取消操作", error);
      }
    },
    async toggleStatus (value) {
      const action = value === 1 ? '启用' : '禁用';
      const url = value === 1 ? this.enableApi : this.disableApi
      try {
        const response = await axios.put(url, this.conf);
        if (response?.code !== 0) {
          this.$message({ type: "error", message: response?.message });
          return;
        }
        this.$message({ type: "success", message: `${action}成功` });
        this.refresh();
      } catch (error) {
        this.$message({ type: "error", message: error.message || '操作失败' });
      }
    },
    refresh () {
      this.$table.search();
    }
  }
}
</script>

<style lang="less" scoped>
</style>